<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Support\Facades\DB;

class UserTree extends BaseModel
{
    use HasDateTimeFormatter;

    protected $table = 'user_trees';
    public $timestamps = false;

    public static function buildUserTree($uid, $pid)
    {
        if (!$pid) {
            return false;
        }

        $_instance = null;
        $parents = self::allParent($pid)->map(function (UserTree $user_tree) use ($uid, &$_instance) {
            $_instance = $user_tree;

            $user_tree->uid = $uid;
            $user_tree->distance += 1;
            return $user_tree->only(['uid', 'pid', 'distance',]);
        })->toArray();

        array_unshift($parents, [
                'uid' => $uid,
                'pid' => $pid,
                'distance' => 1
            ]
        );

        $_instance || $_instance = new UserTree();
        return DB::table($_instance->table)->insert($parents);
    }

    //添加用户树
    public static function addUserTree(User $user)
    {
        if (!$user->rid) {
            if (false) {
                $rowArray[] = [
                    'uid' => $user->id,
                    'pid' => 0,
                    'distance' => 0,
                    'register_at' => $user->created_at
                ];
                return DB::table('user_trees')->insert($rowArray);
            } else {
                return true;
            }
        }
        $userTree = self::getParentCascade($user->id, $user->rid, [], 1, $user->created_at);
        return DB::table('user_trees')->insert($userTree);
    }

    //递归获取上级
    public static function getParentCascade($uid, $upid, $rowArray = [], $distance = 1, $registerTime = "")
    {
        if ($model = User::where('id', $upid)->first()) {
            $rowArray[] = [
                'uid' => $uid,
                'pid' => $upid,
                'distance' => $distance,
                'register_at' => $registerTime,
            ];
            $distance++;
            return self::getParentCascade($uid, $model->rid, $rowArray, $distance, $registerTime);
        }
        return $rowArray;
    }

    //递归获取下级
    public static function getChildrenCascade($data, $uid)
    {
        $arr = [];
        foreach ($data as $key => $val) {
            if ($val['pid'] == $uid) {
                $val['children'] = self::getChildrenCascade($data, $val['uid']);
                $arr[] = $val;
            }
        }
        return $arr;
    }

    public function user()
    {
        return $this->belongsTo(User::class, 'uid', 'id');
    }

    public function parent()
    {
        return $this->belongsTo(User::class, 'pid', 'id');
    }

    public static function getChildrenCount($uid, $distance = 0)
    {
        $model = self::query()->where('pid', $uid);
        if ($distance) {
            $model = $model->where('distance', $distance);
        }
        return $model->count();
    }

    public function getParent($uid, $distance = 0)
    {
        $model = self::query()->where('uid', $uid);
        if ($distance) {
            $model = $model->where('distance', '<=', $distance);
        }
        return $model->select(["pid", "distance"])->get()->toArray();
    }

    public static function allParent($uid)
    {
        return self::whereUid($uid)->orderBy('distance')->get();
    }


    public function history($params)
    {
        return self::list(["*"], ['pid' => $params['uid']]);
    }

    public static function deleteTree($user_id)
    {
        return self::query()->whereIn('uid', $user_id)->delete();
    }
}
